package com.itheima.user.controller;

import com.itheima.sh.entity.OrderEntity;
import com.itheima.sh.entity.UserEntity;
import com.itheima.sh.feign.order.OrderFeign;
import com.itheima.sh.vo.request.AddOrderVO;
import com.itheima.sh.vo.response.OrderResultVO;
import com.itheima.sh.vo.response.ResultVO;
import com.itheima.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/user")
//@CrossOrigin  // 允许所有的前端都可以跨域
public class UserController {

    @Autowired
    private UserService userService;

    //用户登录
    @GetMapping("/login/{userName}/{password}")
    public ResultVO login(@PathVariable("userName") String userName, @PathVariable("password")String password){
        boolean loginResult = userService.login(userName, password);
        ResultVO result = new ResultVO();
        if (loginResult){
            result.setSuccess(true);
        }else {
            result.setSuccess(false);
        }
        return  result;
    }

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    DiscoveryClient discoveryClient;

    @Autowired
    OrderFeign orderFeign;// 基于JDK动态代理，获取到url 发起远程调用， 动态代理对象存到 IOC容器

    //查询用户订单信息
    @GetMapping("/findUserOrders/{userId}")
    public OrderResultVO findUserOrders(@PathVariable("userId") Integer userId, HttpServletRequest request) {

        UserEntity userEntity = userService.findUserById(userId);

        /**
         * 1、IP和端口号 硬编码问题
         * 2、服务请求路径 硬编码问题
         * 3、存在高并发不可用问题， 不能负载均衡调用服务的提供方
         */
        //todo 查询当前用户的订单列表
//        String url = "http://localhost:9001/order/findOrderInfoByUserId/"+userId;

        // 1、解决：IP和端口号 硬编码问题   注册中心 根据 order-service 拉取服务对应的 IP和PORT
//        List<ServiceInstance> instances = discoveryClient.getInstances("order-service");
//        ServiceInstance serviceInstance = instances.get(0);  // 服务实例对象
//        String host = serviceInstance.getHost(); // IP 主机
//        int port = serviceInstance.getPort();// PORT 端口
//        String url = "http://"+host+":"+port+"/order/findOrderInfoByUserId/"+userId;


        // 3、解决：存在高并发不可用问题， 不能负载均衡调用服务的提供方
        // 负载均衡算法：默认是 轮询
//        String url = "http://order-service/order/findOrderInfoByUserId/"+userId;
        // 发起远程调用
//        List list = restTemplate.getForObject(url, List.class);

        //2、解决：服务请求路径 硬编码问题，  面向接口的远程调用
        List<OrderEntity> list = orderFeign.findOrderInfoByUserId(userId);

        OrderResultVO orderResultVO = OrderResultVO.builder().userName(userEntity.getUserName()).orderList(list).build();

//        String str = orderFeign.findAll();
//        System.out.println(str);


        String company = request.getHeader("company");
        System.out.println(company);

        return orderResultVO;
    }

    //添加订单
    @PostMapping("/addUserOrder")
    public ResultVO addUserOrder(@RequestBody AddOrderVO addOrderVO){
        ResultVO result = new ResultVO();
        //判断用户是否存在
        UserEntity userEntity = userService.findUserById(addOrderVO.getUserId());
        if (userEntity == null){
            result.setSuccess(false);
            return result;
        }

        //todo

        return result;
    }
}
